import _ from "lodash";
import {RouteRecordRaw} from "vue-router";
import {AppRoute, AppRoutes} from "./app-router-type";

function buildVueRouteRecord(
    route: AppRoute<any>,
    routes: AppRoutes<any>
): RouteRecordRaw {
  const result: RouteRecordRaw = {
    ...route,
    children: null,
  };
  _.forOwn(routes, (value, key, object) => {
    if (value === route) {
      return;
    }

    if (!value.layout) {
      return;
    }

    const layout: AppRoute<any> =
        typeof value.layout === "function" ? value.layout(routes) : value.layout;
    if (layout !== route) {
      return;
    }

    const child = buildVueRouteRecord(value, routes);
    if (!result.children) {
      result.children = [child];
      return;
    }

    result.children.push(child);
  });

  return result;
}

export default {
  convertToVueRoutes(appRoutes: AppRoutes<any>): Readonly<RouteRecordRaw[]> {
    const topRouteSet = new Set<AppRoute<any>>();
    _.forOwn(appRoutes, (value, key, object) => {
      if (!value.layout) {
        topRouteSet.add(value);
      }
    });

    const result: RouteRecordRaw[] = [];
    topRouteSet.forEach((value) => {
      const routeRecord = buildVueRouteRecord(value, appRoutes);
      result.push(routeRecord);
    });
    return result;
  },
};
